<script>
import Axios from 'axios'
import { aiWriteTargetList } from './template.js'
import officeTemp from './component/officeTemp.vue' //公文模版库
import insTools from './component/insTools.vue' //灵感工具

import aiForm from './component/aiForm.vue'
import aiList from './component/aiList.vue'
import aiFinal from './component/aiFinal.vue'
import aiSteps from './component/aiSteps.vue'
export default {
  components: {
    officeTemp,
    insTools,
    aiForm,
    aiList,
    aiFinal,
    aiSteps,
  },
  data() {
    return {
      aiWriteTargetList,
      activeIndex: 1,
      activeName: '公文模板库',
      totalLen: 0, // 总长度
      writeSrrr: '',
      currentReadLen: 0, // 当前读取长度
      loading: false,
      chartFlag: false,
      docType: '',
      recordProcess: '0%',
      finalStatus: null, // 0.停止生成 1.生成完成 2.正在生成
      setTimeoutId: null,
      signal: null,
      olConfigData: [],
      showButtonList: [],
      formConfigList: [],
      documentDataList: [],
      activeList: [
        {
          select: 1,
          img: require('@/static/img/word_default.png'),
          aImg: require('@/static/img/word_select.png'),
          name: '公文模板库',
        },
        {
          select: 2,
          img: require('@/static/img/AI_default.png'),
          aImg: require('@/static/img/AI_select.png'),
          name: 'AI写作',
        },
        {
          select: 3,
          img: require('@/static/img/mb_default.png'),
          aImg: require('@/static/img/mb_select.png'),
          name: '灵感工具',
        },
      ],
      currentPoint: {},
      currentTarget: {},
      formConfigData: {},
      configFormRules: {},
      recordParamsData: {},
      mainPointData: new Map(),
      // controller: new AbortController(),//是 JavaScript 中用于取消异步操作的 API
      controller: null,

      //cx 领导讲话记录回退类型
      remberBackType: '',
      docContent: '',

      //记录流字符串
      remberStr: '',
      newStrsss: '', //记录doc字符串
      writeTms: null,
      //记录写稿长度位置
      writelength: 0,
      receivedBytes: 0,
      estimatedTotalBytes: 1024, // 初始估计的总长度
    }
  },
  computed: {
    tabList() {
      return this.activeList
    },

    // 模版数据
    NewaiWriteTargetList() {
      return aiWriteTargetList
    },
    contentClass() {
      if (
        this.currentTarget.hasMainPoint &&
        this.currentPoint.value !== 'MANUSCRIPT'
      ) {
        return 'writing-ai-point'
      } else {
        return 'main_form'
      }
    },

    userInfo() {
      return JSON.parse(window.localStorage.getItem('LoginInfo'))
    },
    hasPermission() {
      return (
        this.userInfo.compid === '1' ||
        this.userInfo.compid === 'f5b9d842-2d9f-4a87-9dfc-ad7465c86422' ||
        this.userInfo.compid === '091e402a-1989-4ea4-9690-844a8c186ee6'
      )
    },
    mapKey() {
      return `${this.currentTarget.value}_${this.currentPoint.value}`
    },
  },
  beforeDestroy() {
    if (this.writeTms) clearInterval(this.writeTms)
  },

  methods: {
    handleSelect(tab) {
      // console.log(tab);
      this.activeIndex = tab.select
      this.activeName = tab.name
      tab.select === 2 && this.handleClickTarget(this.NewaiWriteTargetList[0])
    },
    // 切换写作目的
    handleClickTarget(target) {
      this.currentTarget = target
      this.handleStep(target.pointList[0], 'refresh')
    },
    handleStep(step, flag = 'init') {
      this.currentPoint = step
      // debugger
      this.handleInit(flag)
    },
    /**
     * form-表单项/表单校验/表单数据
     * ol-大纲列表/列表数据
     * button-操作按钮
     */
    handleInit(isReset) {
      // debugger
      this.formConfigList = JSON.parse(
        JSON.stringify(this.currentPoint.config.formList)
      )
      this.showButtonList =
        this.finalStatus === 2
          ? this.currentPoint.config.stopList
          : this.currentPoint.config.buttonList
      if (this.currentPoint.type === 'form') {
        this.configFormRules = this.currentPoint.config.formRules
        // debugger;
        // console.log(this.docType);
        // console.log(this.formConfigData);
        // console.log(this.remberBackType);
        //修改前
        // this.handleChangeForm(this.currentPoint.config.documentType, isReset);

        //cx修改后cx 修改领导讲话 返回不能回退问题
        if (
          this.formConfigData &&
          this.formConfigData.document_type &&
          this.formConfigData.document_type === '领导讲话'
        ) {
          this.remberBackType = this.formConfigData.document_type //记录当前类型
        } else if (this.formConfigData && this.formConfigData.document_type) {
          //其他情况情况不影响
          this.remberBackType = ''
        }
        if (
          this.remberBackType === '领导讲话' &&
          isReset === 'init' &&
          !this.formConfigData.document_type
        ) {
          this.handleChangeForm(this.remberBackType, isReset)
        } else {
          this.handleChangeForm(this.currentPoint.config.documentType, isReset)
        }
      } else if (this.currentPoint.type === 'ol') {
        let list = this.formConfigList[0].pointList || []
        try {
          let flag = this.mainPointData.has(this.mapKey)
          this.olConfigData = flag
            ? this.olConfigData.length
              ? this.olConfigData
              : list
            : list
        } catch (error) {}
      }
    },

    handleChangeForm(value, flag = 'refresh') {
      // debugger
      this.docType = value
      this.getFormDataList(flag)
    },

    getFormDataList(isReset) {
      // debugger
      let flag = this.mainPointData.has(this.mapKey)
      isReset === 'refresh' && (flag = false)
      let formList = []
      let formData = {}
      this.currentPoint.config.formList.map((temp) => {
        // debugger
        let aliasList = this.docType
          ? temp.itemList.filter((el) => el.typeAlias.includes(this.docType))
          : temp.itemList
        formList.push({
          ...temp,
          itemList: aliasList,
        })
        if (!flag) {
          aliasList.map((item) => {
            if (item.default) {
              formData[item.prop] = this.docType
            } else {
              formData[item.prop] = this.hasPermission ? item.gyLabel || '' : ''
            }
            // 参考文件参数
            item.aliasProp && (formData[item.aliasProp] = [])
            item.formData && (formData[item.formData] = '')
          })
        }
      })
      this.mainPointData.set(
        this.mapKey,
        flag ? this.mainPointData.get(this.mapKey) : formData
      )
      // debugger
      this.formConfigList = [...formList]
      this.formConfigData = flag
        ? this.mainPointData.get(this.mapKey)
        : formData
    },

    handleNext(option) {
      const currentIndex = this.currentTarget.pointList.findIndex(
        (el) => el.value === this.currentPoint.value
      )
      switch (option.value) {
        case 'start':
          this.mainPointData = new Map() // 缓存数据重置
          this.handleStep(this.currentTarget.pointList[0])
          break

        case 'stop':
          this.finalStatus = 0 // 停止生成
          if (this.writeTms) clearInterval(this.writeTms) //清除写的定时器
          this.showButtonList = this.currentPoint.config.buttonList
          this.setTimeoutId && window.clearTimeout(this.setTimeoutId) // 停止文稿输入
          !this.signal.aborted && this.controller.abort() // 停止接口请求
          this.handleFetchController()
          break

        case 'previous':
          // debugger
          if (this.currentPoint.type === 'ol') {
            let data = this.$refs.aiWriteOlRef.getPointDataList()
            this.mainPointData.set(this.mapKey, data)
            this.olConfigData = data
          }
          this.handleStep(this.currentTarget.pointList[currentIndex - 1])
          break

        case 'AI_create_article': // 基于基本信息/摘要
          if (this.currentPoint.type === 'form') {
            const flag = this.$refs.aiWriteFormRef.handleConfirm()
            if (flag) {
              this.finalStatus = 2 // 正在生成
              this.handleStep(this.currentTarget.pointList[currentIndex + 1])

              let { aiData, formData } =
                this.$refs.aiWriteFormRef.handleSubmit()
              this.mainPointData.set(this.mapKey, formData)
              let params = aiData
              if (this.currentTarget.hasMainPoint) {
                params = this.getAllParams()
              }
              //cx文稿类型===领导讲话 去掉多余项
              if (formData.document_type === '领导讲话') {
                this.removeProperties(
                  params,
                  '参考文件',
                  '发言人身份',
                  '发言目的',
                  '听众角色',
                  '形势与优势关键词',
                  '形势与优势观点',
                  '推介与理论引用关键词',
                  '推介描述观点',
                  '讲话主题',
                  '讲话场景'
                )
              }

              this.handleSubmit(option.content, params)
            }
          }
          break

        case 'create_abstract':
          if (this.currentPoint.type === 'form') {
            const flag = this.$refs.aiWriteFormRef.handleConfirm()
            if (flag) {
              let { aiData, formData } =
                this.$refs.aiWriteFormRef.handleSubmit()
              this.mainPointData.set(this.mapKey, formData)
              this.getNextContent(option.content, aiData)
            }
          }
          break

        case 'AI_create_summary':
          if (this.currentPoint.type === 'form') {
            const flag = this.$refs.aiWriteFormRef.handleConfirm()
            if (flag) {
              let { formData } = this.$refs.aiWriteFormRef.handleSubmit()
              this.mainPointData.set(this.mapKey, formData)
              this.handleStep(this.currentTarget.pointList[currentIndex + 1])
            }
          }
          break

        case 'only_main_point':
          if (this.currentPoint.type === 'ol') {
            let data = this.$refs.aiWriteOlRef.getPointDataList()
            this.mainPointData.set(this.mapKey, data)
            this.olConfigData = data
            let text = ''
            data.map((item) => {
              text += `${item.title}\n`
              item.list.map((el, index) => {
                text += `${index + 1}. ${el.label}\n`
              })
            })
            let doc = wps.WpsApplication().ActiveDocument
            let myRange = doc.Range(0, doc.Content.End - 1)
            myRange.InsertParagraph()
            myRange.InsertAfter(text)
            doc.Range(doc.Content.End, doc.Content.End).Select()
          }
          break

        case 'basic_point': // 基于基本信息/摘要/大纲
          if (this.currentPoint.type === 'ol') {
            let data = this.$refs.aiWriteOlRef.getPointDataList()
            this.mainPointData.set(this.mapKey, data)
            this.olConfigData = data
            let text = ''
            data.map((item) => {
              text += `${item.title}\n`
              item.list.map((el, index) => {
                text += `${index + 1}. ${el.label}\n`
              })
            })
            let params = this.getAllParams()
            this.finalStatus = 2 // 正在生成
            this.handleStep(this.currentTarget.pointList[currentIndex + 1])
            this.handleSubmit(option.content, { ...params, 大纲: text })
          }
          break

        case 'basic_summary': // 基于基本信息和摘要
          if (this.currentPoint.type === 'ol') {
            let data = this.getAllParams()
            this.finalStatus = 2 // 正在生成
            this.handleStep(this.currentTarget.pointList[currentIndex + 1])
            this.handleSubmit(option.content, data)
          }
          break

        default:
          break
      }
    },

    // 下一步生成摘要
    getNextContent(content, data) {
      this.loading = true
      let params = {
        model: '',
        stream: false,
        max_tokens: 1500,
        messages: [
          {
            role: 'user',
            content: content,
            文种: this.currentTarget.label,
            ...data,
          },
        ],
      }
      // 记录生成参数
      this.recordParamsData = params
      var config = {
        method: 'post',
        url: 'http://gwdmx.dacube.com.cn/',
        headers: {
          Authorization: 'Basic Z3B1YXBpOnEjYmU3N0xlalZzMDE=',
          'Content-Type': 'application/json',
        },
        data: JSON.stringify(params),
      }
      var _this = this
      Axios(config)
        .then(function (response) {
          console.log(response)
          if (response && response.data && response.data.choices[0]) {
            let text = response.data.choices[0].message.content
            // 开始写入正文
            const pointIndex = _this.currentTarget.pointList.findIndex(
              (el) => el.value === _this.currentPoint.value
            )
            let absList = _this.currentTarget.pointList[pointIndex + 1]
            let nextData = {}

            absList.config.formList.map((list) => {
              list.itemList.map((el) => {
                let str = text
                // console.log(str);
                // console.log(str.replace(/<br>/g,'\n'))
                nextData[el.prop] = str.replace(/<br>/g, '\n')
              })
            })
            const key = `${_this.currentTarget.value}_${absList.value}`
            _this.mainPointData.set(key, nextData)
            _this.handleStep(absList)
          }
        })
        .catch(function (error) {
          console.log(error)
          // _this.$notify.error('接口异常,稍后再试2！')
        })
        .finally(() => {
          _this.loading = false
        })
      // window
      //   .fetch('http://gwdmx.dacube.com.cn/', {
      //     method: 'POST',
      //     headers: {
      //       'Content-Type': 'application/json',
      //       Authorization: 'Basic Z3B1YXBpOnEjYmU3N0xlalZzMDE=',
      //     },
      //     body: JSON.stringify(params),
      //   })
      //   .then((response) => {
      //     this.loading = false;
      //     response.json().then((res) => {
      //       const pointIndex = this.currentTarget.pointList.findIndex((el) => el.value === this.currentPoint.value);
      //       let absList = this.currentTarget.pointList[pointIndex + 1];
      //       let nextData = {};

      //       absList.config.formList.map((list) => {
      //         list.itemList.map((el) => {
      //           let str = res.choices[0].message.content;
      //           // console.log(str);
      //           // console.log(str.replace(/<br>/g,'\n'))
      //           nextData[el.prop] = str.replace(/<br>/g, '\n');
      //         });
      //       });
      //       const key = `${this.currentTarget.value}_${absList.value}`;
      //       this.mainPointData.set(key, nextData);
      //       this.handleStep(absList);
      //     });
      //   })
      //   .catch((error) => {
      //     this.$notify.error('接口异常,稍后再试！');
      //     this.loading = false;
      //     console.error('发生错误:', error);
      //   });
    },

    handleSubmit(content, data) {
      this.loading = true
      this.chartFlag = true
      this.currentReadLen = 0
      this.documentDataList = []

      this.recordProcess = '0%' //重置精度条
      this.remberStr = '' //清空记录流的记录
      this.newStrsss = ''
      this.writelength = 0
      this.receivedBytes = 0
      this.estimatedTotalBytes = 1024 //默认
      // 清除文章内容
      try {
        window.c_methods.replaceRangeText(0, 999999, '')
      } catch (error) {
        console.log(error)
      }
      if (this.writeTms) clearInterval(this.writeTms)

      let params = {
        model: '',
        stream: false,
        max_tokens: 4000,
        messages: [
          {
            role: 'user',
            content: content,
            文种: this.currentTarget.label,
            ...data,
          },
        ],
      }
      this.recordParamsData = params
      let titleS = data['文稿标题'] || ''

      var config = {
        method: 'post',
        url: 'http://gwdmx.dacube.com.cn/',
        headers: {
          Authorization: 'Basic Z3B1YXBpOnEjYmU3N0xlalZzMDE=',
          'Content-Type': 'application/json',
        },
        data: JSON.stringify(params),
      }
      var _this = this
      Axios(config)
        .then(function (response) {
          if (response && response.data && response.data.choices[0]) {
            let text = response.data.choices[0].message.content
            // 开始写入正文
            _this.writeStringZengWen(titleS, text)
          }
        })
        .catch(function (error) {
          this.$notify.error('接口异常,稍后再试！')
        })
        .finally(() => {
          this.loading = false
        })
      // debugger

      // window
      //   .fetch('http://gwdmx.dacube.com.cn/', {
      //     method: 'POST',
      //     headers: {
      //       'Content-Type': 'application/json',
      //       Authorization: 'Basic Z3B1YXBpOnEjYmU3N0xlalZzMDE=',
      //     },
      //     // signal: this.controller.signal,
      //     body: JSON.stringify(params),
      //   })
      //   .then((response) => {
      //     // console.log(response);
      //     if (!response.ok) {
      //       this.$notify.error('接口异常,稍后再试！');
      //       return;
      //     }
      //     this.loading = false;
      //     return response.json();
      //   })
      //   .then((result) => {
      // if (titleS) {
      //   titleS = titleS.trim();
      //   this.remberStr += `${titleS}\n\n`;
      //   let rng = window.Application.ActiveDocument.Range(0, titleS.length + 2);
      //   if (rng) {
      //     rng.Font.Bold = true;
      //     rng.Font.Name = '方正小标宋'; //仿宋_GB2312
      //     rng.Font.Size = 18;
      //     rng.ParagraphFormat.Alignment = 1;
      //   }
      //   for (var i = 0; i < this.remberStr.length; i++) {
      //     let doc = wps.ActiveDocument;
      //     let selection = wps.Selection;
      //     selection.Start = doc.Content.End;
      //     selection.End = doc.Content.End;
      //     selection.Range.Select();
      //     selection.TypeText(this.remberStr[i]);
      //   }
      // }
      // // console.log(result.choices[0].message.content);
      // let rng = window.Application.ActiveDocument.Range(titleS.length + 2, titleS.length + 2);
      // if (rng) {
      //   // console.log('-rng.Font',rng.Font);
      //   rng.Font.Bold = false;
      //   rng.Font.Name = '仿宋_GB2312'; //宋体 仿宋_GB2312
      //   // rng.Font.Color='#000000'
      //   rng.Font.Size = 16;
      //   rng.ParagraphFormat.Alignment = 0;
      // }

      // this.writeString(result.choices[0].message.content);
      // })
      // .catch((error) => {
      //   if (this.finalStatus !== 0) {
      //     this.$notify.error('接口异常,稍后再试！');
      //   }
      //   this.loading = false;
      //   if (this.chartFlag) {
      //     this.chartFlag = false;
      //     this.finalStatus = 0; // 停止生成
      //     this.showButtonList = this.currentPoint.config.buttonList;
      //     this.setTimeoutId && window.clearTimeout(this.setTimeoutId); // 停止文稿输入
      //     !this.signal.aborted && this.controller.abort(); // 停止接口请求
      //     this.handleFetchController();
      //   }
      //   console.error('发生错误:', error);
      // })
      // .finally(() => {
      //   this.loading = false;
      // });
    },

    // 写入正文
    writeStringZengWen(title, strings) {
      try {
        window.c_methods.replaceRangeText(0, 999999, '')
        if (title) {
          if (window.c_methods && window.c_methods.replaceRangeText) {
            window.c_methods.replaceRangeText(0, title.length + 1, title + '\n')
            window.c_methods.setRangeFont(0, title.length + 1, {
              name: '方正小标宋',
              size: 18,
              bold: 1,
              italic: 0,
            })
            // "Alignment": 0, //对齐方式 0:左对齐 1:居中对齐 2：右对齐 3： 两端对齐 4： 分散对齐
            //     "LineSpacing": 28, // 行距
            //     "LineSpacingRule": 4, // 行距类型
            //     "LineUnitBefore": 0, // 段前间距
            //     "LineUnitAfter": 0, // 段后间距
            //     "CharacterUnitLeftIndent": 0, // 左缩进量
            //     "CharacterUnitRightIndent": 0, // 右缩进量
            //     "CharacterUnitFirstLineIndent": 2.21 // 首行缩进
            window.c_methods.setParagraphStyle(0, {
              alignment: 1, //居中对齐
              lineSpacing: 28,
              lineSpacingRule: 4,
              spaceBefore: 0,
              spaceAfter: 0,
              leftIndent: 0,
              rightIndent: 0,
              firstLineIndent: -10,
            })
          }
        }

        if (strings) {
          // let text = '你好呀\n我是哈哈哈2如果 ReplaceSelection 属性为 True，则用指定文本替换选定内容。如果 ReplaceSelection 为 False，则在选定内容之前插入指定的文本。'
          let text = strings
          text = text
            .replace(/\t/g, '')
            .replace(/<br\/?>/g, '\n') // 替换 <br> 和 <br/> 为换行符
            .replace(/<b>/g, '') // 移除 <b>
            .replace(/<emsp;/g, '\u3000') // 替换 <emsp; 为全角空格
            .replace(/&nbsp;/g, '\u3000') // 替换 &nbsp; 为全角空格（用于缩进）
          strings = this.replaceDateWithStars(text)
          if (!strings) {
            this.finalStatus = 1 // 生成完成
            this.showButtonList = this.currentPoint.config.buttonList
            this.recordProcess = '100%'
            return
          }
          this.finalStatus = 2 // 正在生成  //0.停止生成 1.生成完成 2.正在生成
          this.totalLen = strings.length
          var titleRanSatrt = title.length + 1
          // console.log('标题结束位置：' + titleRanSatrt)
          var writelength = 0

          var score = 0

          window.c_methods.setRangeFont(titleRanSatrt, 999999, {
            name: '仿宋_GB2312',
            size: 16,
            bold: 0,
            italic: 0,
          })
          window.c_methods.setParagraphStyle(1, {
            alignment: 0, //左对齐
            lineSpacing: 28,
            lineSpacingRule: 4,
            spaceBefore: 0,
            spaceAfter: 0,
            leftIndent: 0,
            rightIndent: 0,
            firstLineIndent: 30,
          })
          // 方案一
          // window.c_methods.replaceRangeText(titleRanSatrt, 9999999,strings)

          // 方案二
          if (this.writeTms) clearInterval(this.writeTms)
          this.writeTms = setInterval(() => {
            if (writelength >= strings.length - 1) {
              this.recordProcess = '100%'
              this.finalStatus = 1 // 生成完成
              this.showButtonList = this.currentPoint.config.buttonList
              if (this.writeTms) clearInterval(this.writeTms)
            }

            let str =
              (strings[writelength] ? strings[writelength] : '') +
              (strings[writelength + 1] ? strings[writelength + 1] : '') +
              (strings[writelength + 2] ? strings[writelength + 2] : '') +
              (strings[writelength + 3] ? strings[writelength + 3] : '') +
              (strings[writelength + 4] ? strings[writelength + 4] : '')
              //下标滚动跟随
            if((writelength+4)%100){
              // window.alert(writelength+4)
              window.c_methods.selectRange(writelength+9,writelength+9)
            }
            window.c_methods.replaceRangeText(
              titleRanSatrt + writelength,
              titleRanSatrt + writelength + 1,
              // strings[writelength]+strings[writelength+1]
              // strings[writelength]
              str
            )

            score = (writelength / this.totalLen) * 100
            if (score > 100) {
              this.recordProcess = `100%`
            } else {
              this.recordProcess = `${parseInt(score)}%`
            }
            // console.log(strings[writelength],titleRanSatrt + writelength, titleRanSatrt + writelength+1)
            writelength += 5
            this.writeSrrr += strings[writelength]

            
          }, 70)
        }
      } catch (error) {
        if (this.writeTms) clearInterval(this.writeTms)
      }
    },

    //正则替换
    replaceDateWithStars(text) {
      text = text.replace(/(<br>\s*){5,}/g, '<br><br>')
      //console.log(text);
      // 贺耕耘哈哈周年庆
      const regex1 = /\d{2,4}年(?:\d{1,2}月)?(?:\d{1,2}日)?/g // 匹配日期格式 1898年7月29日
      text = text.replace(regex1, '****年**月**日')
      // const regex2 = /[\u4e00-\u9fa5]{4}年([\u4e00-\u9fa5]+月)?([\u4e00-\u9fa5]+日)?/g; // 匹配日期格式 二零零零年七月二十七日
      let regex0 =
        /(\d{2,4}|[\u4e00-\u9fa5]{4})年(?:(\d{1,2}|[\u4e00-\u9fa5]{1,2})月)+(?:(\d{1,2}|[\u4e00-\u9fa5]{1,3})日)+/g
      text = text.replace(regex0, '****年**月**日')

      const regex3 =
        /\d+(户|个贫困村|个贫困县|年|月|日|人|个|个人|元|万元|百万元|千万元|亿元)/g
      text = text.replace(regex3, '**$1')

      const regex4 = /〔(\d{4})〕(\d+)号/g
      text = text.replace(regex4, '〔****〕*号')

      //手机号
      const regex5 =
        /(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}/g
      text = text.replace(regex5, '***********')

      //座机号
      // const regex7 = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/g
      // text = text.replace(regex7, (match) => '*'.repeat(match.length));
      const regex8 = /0\d{11}/g
      text = text.replace(regex8, () => '*'.repeat(11))

      //邮箱
      const regex6 = /\b[A-Za-z0-9._%+-]+@(qq|163|126)\.com\b/g
      text = text.replace(regex6, '****@****')

      //无意义字符
      const regex9 = /<\/?([a-z][a-z0-9]*)\b[^>]*>/g
      text = text.replace(regex9, '')
      return text
    },

    handleFetchController() {
      try {
        this.controller = new AbortController()
        this.signal = this.controller.signal
        this.signal.addEventListener('abort', () => {
          console.log('取消生成！')
        })
      } catch (error) {}
    },
    // 获取基本信息/摘要
    getAllParams() {
      const currentIndex = this.currentTarget.pointList.findIndex(
        (el) => el.value === this.currentPoint.value
      )
      let data = {}
      // 基本信息
      let basicList = this.currentTarget.pointList[currentIndex - 2]
      const basicKey = `${this.currentTarget.value}_${basicList.value}`
      let basicData = this.mainPointData.get(basicKey)
      basicList.config.formList.map((temp) => {
        let aliasList = this.docType
          ? temp.itemList.filter((el) => el.typeAlias.includes(this.docType))
          : temp.itemList
        aliasList.map((el) => {
          data[el.label] = basicData[el.prop]
        })
      })
      // 摘要信息
      let abstractList = this.currentTarget.pointList[currentIndex - 1]
      const abstractKey = `${this.currentTarget.value}_${abstractList.value}`
      let abstractData = this.mainPointData.get(abstractKey)
      abstractList.config.formList.map((temp) => {
        let aliasList = this.docType
          ? temp.itemList.filter((el) => el.typeAlias.includes(this.docType))
          : temp.itemList
        aliasList.map((el) => {
          data[el.label] = abstractData[el.prop]
        })
      })
      return data
    },
  },
}
</script>

<template>
  <flex class="writing">
    <div class="writing-header-tab">
      <flex
        v-for="tab in tabList"
        :key="tab.select"
        :class="{ select: activeIndex === tab.select }"
        align="center"
        direction="column"
        class="tab-item"
        @click="handleSelect(tab)"
      >
        <img
          :src="activeIndex === tab.select ? tab.aImg : tab.img"
          :alt="tab.name"
          class="tab-img"
        />
        <p v-if="tab.select === 1" class="tab-text">公文<br />模板库</p>
        <p v-else class="tab-text">{{ tab.name }}</p>
      </flex>
    </div>
    <div v-loading="loading" class="writing-header-wrapper-all">
      <flex align="center" justify="between" class="writing-header-title">
        <div class="write-target-title">{{ activeName }}</div>
        <div v-if="activeIndex === 2" align="center" class="write-target-box">
          <span>写作目的</span>
          <el-select
            v-model="currentTarget"
            filterable
            style="width: 70%"
            value-key="value"
            size="small"
            class="write-target-select"
            popper-class="write-target-popper"
            @change="handleClickTarget"
          >
            <el-option
              v-for="(item, index) in NewaiWriteTargetList"
              :key="index"
              :value="item"
              :label="item.label"
            />
          </el-select>
        </div>
      </flex>
      <div v-if="activeIndex === 2" class="writing-header-ai">
        <aiSteps
          v-if="
            currentTarget.hasMainPoint && currentPoint.value !== 'MANUSCRIPT'
          "
          :current="currentPoint.value"
          :steps-list="currentTarget.pointList"
          class="ai-steps"
        />
        <div :class="contentClass">
          <el-scrollbar class="main-scroll" style="overflow-x: hidden">
            <aiForm
              v-show="currentPoint.type === 'form'"
              ref="aiWriteFormRef"
              :form-rules="configFormRules"
              :config-form-data="formConfigData"
              :config-form-list="formConfigList"
              class="write_content"
              @change="handleChangeForm"
            />
            <aiList
              v-show="currentPoint.type === 'ol'"
              ref="aiWriteOlRef"
              :config-ol-data="olConfigData"
              :config-ol-list="currentPoint.config.formList"
              class="ol_content"
            />
            <aiFinal
              v-if="currentPoint.type === 'end'"
              :final-status="finalStatus"
              :processText="recordProcess"
              :record-data="recordParamsData"
              :config-form-list="formConfigList"
              class="write_final"
            >
            </aiFinal>
          </el-scrollbar>
        </div>
      </div>
      <flex
        v-if="activeIndex === 2"
        class="button_list"
        align="center"
        justify="center"
      >
        <el-button
          v-for="(btn, index) in showButtonList"
          :key="btn.value + index"
          :type="btn.type"
          size="mini"
          @click="handleNext(btn)"
        >
          {{ btn.name }}
        </el-button>
      </flex>
      <officeTemp v-if="activeIndex === 1" class="writing-header-temp" />
      <!--灵感工具 -->
      <insTools v-if="activeIndex === 3" class="ins-header-temp" />
    </div>
  </flex>
</template>

<style scoped>
@import './writing.css';
</style>
